﻿using dal.cgm_production_dao;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using utils;

namespace inner_label_printing
{
    public partial class Form1 : Form
    {
        private System.Windows.Forms.Timer validationTimer;

        public Form1()
        {
            InitializeComponent();
            // 初始化计时器
            validationTimer = new System.Windows.Forms.Timer();
            validationTimer.Interval = 500; // 延迟500毫秒
            validationTimer.Tick += new EventHandler(ValidationTimer_Tick);
            versionLabel.Text = "v" + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();

        }

        /// <summary>
        /// dmText_TextChanged
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dmText_TextChanged(object sender, EventArgs e)
        {
            // 每次文本改变时重置计时器
            validationTimer.Stop();
            validationTimer.Start();
        }

      

        private async void ValidationTimer_Tick(object sender, EventArgs e)
        {
            validationTimer.Stop(); // 停止计时器
            label2.Text = string.Empty;
            #region 参数校验
            string qrCode = qrText.Text;
            if (!Regex.IsMatch(qrCode, "^[0-9A-Z]{12}$"))
            {
                qrText.BackColor = Color.LightCoral;
                HandleError("助针器码格式校验失败");
            }
            AppendLog($"助针器码: {qrCode} 格式校验成功", true);
            ApiLog.Debug($"助针器码: {qrCode} 格式校验成功");
            qrText.BackColor = Color.LightGreen;
            #endregion

            var client = new HttpClientHelper(ConfigurationManager.AppSettings["ServerUrl"]);
            var productionCode =ConfigurationManager.AppSettings["ProductionCode"]; //铝箔袋上产品代码

            // 示例：发送JSON请求
            var jsonRequest = new
            {
                production_code = productionCode,
                mac_address = qrCode,
                sc = "30b9c3ca5e9911ef9aa806433e9aa661",
                sv = "70k9c3ca9e9911ef9aa806433e9aju65"
            };

            try
            {
                string jsonResponse = await client.PostJsonAsync("/api/InnerPrint", jsonRequest);

                var response = JsonConvert.DeserializeObject<ApiResponse>(jsonResponse);
                if (response.Code == 200)
                {
                    var res = JsonConvert.DeserializeObject<InnerPrintApiResponse>(jsonResponse);

                    var reportPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "inner_label.frx");
                    FastReport.Report report = new FastReport.Report();
                    report.Load(reportPath);

                    var model = new
                    {
                        //Mac = qrCode,
                        ProductionCode = productionCode,
                        ProductionDate = res.Data.ProductionDate,
                        ExpiryDate = res.Data.ExpiryDate,
                        ProductionBatch = res.Data.ProductionBatch,
                        SerialCode = res.Data.SerialCode,
                    };

                    //刷选可以打印字段特性的模型属性
                    var list = model.GetType().GetProperties();
                    //批量设置打印模板参数值
                    foreach (PropertyInfo pro in list)
                    {
                        var value = pro.GetValue(model, null);
                        //获取参数
                        FastReport.Data.Parameter param = report.Parameters.FindByName(pro.Name);
                        if (param != null)
                        {

                            param.Value = value; //将属性的值赋值给名字相同的报表参数
                        }
                    }
                    report.PrintSettings.Printer = "ZDesigner ZT510-300dpi ZPL"; // 设置默认打印机
                    report.PrintSettings.ShowDialog = false; // 禁止显示打印对话框
                    report.Prepare();
                    if (checkViewPrint.Checked)
                    {
                        report.ShowPrepared();
                    }
                    else
                    {           
                        // 直接打印报表
                        report.Print();

                    }
        

                    // 释放使用的资源
                    report.Dispose();

                    ResetDmText();
                    label2.Visible = true;
                    label2.ForeColor = Color.Green;
                    label2.Text = "打印成功";
                }
                else
                {
                    HandleError(response.Message);
                }

                // 处理 jsonResponse 的逻辑
            }
            catch(Exception  ex)
            {
                HandleError(ex.Message);
            }
        }

        /// <summary>
        /// HandleError
        /// </summary>
        /// <param name="message"></param>
        private void HandleError(string message)
        {
            label2.Visible = true;
            label2.ForeColor = Color.Red;
            label2.Text = message;

            AppendLog($"助针器码: {qrText.Text} {message}", false);
            ApiLog.Debug($"助针器码: {qrText.Text} {message}");
            ResetDmText();

        }

        /// <summary>
        /// ResetDmText
        /// </summary>
        private void ResetDmText()
        {
            // 暂时禁用 TextChanged 事件处理程序
            qrText.TextChanged -= dmText_TextChanged;
            // 清空文本框并重置背景颜色
            qrText.Text = "";
            //dmText.BackColor = Color.White;

            // 重新启用 TextChanged 事件处理程序
            qrText.TextChanged += dmText_TextChanged;

            // 聚焦到 dmText
            qrText.Focus();
        }

        /// <summary>
        /// AppendLog
        /// </summary>
        /// <param name="message"></param>
        /// <param name="isError"></param>
        private void AppendLog(string message, bool isError)
        {
            // 选择文本颜色
            Color textColor = isError ? Color.Black : Color.Red;

            // 设置光标位置并插入文本
            logRichTextBox.SelectionStart = logRichTextBox.TextLength;
            logRichTextBox.SelectionLength = 0; // 取消任何选择

            logRichTextBox.SelectionColor = textColor; // 设置颜色
            logRichTextBox.AppendText(message + "\n"); // 添加文本
            logRichTextBox.SelectionColor = logRichTextBox.ForeColor; // 恢复默认颜色
            logRichTextBox.ScrollToCaret(); // 自动滚动到最后
        }

        /// <summary>
        /// 清空日志
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void clearLogButton_Click(object sender, EventArgs e)
        {
            logRichTextBox.Clear();
        }
    }
}
